<?php
/**
 * @file : articlepoint.php
 * @date : 2015-01-19
 */
namespace haibao\cms\data;

class ArticlePoint extends \haibao\cms\data\BaseMysql{

	private $articleBaseContent = array();
    public function __construct(){
        parent::__construct('\haibao\cms\model\data\ArticlePoint');
    }

    /**
     * 添加文章看点
     * @param : Array \haibao\cms\model\data\ArticlePoint 
     * @param : Int $articleId  
     */
    public function saveArticlePoint($articlePointModels,$articleId){

    	// DO : 删除上一次的文章看点
    	$sql = 'delete from `ArticlePoint` where ArticleId=%s';
    	$this->query($sql,array($articleId));
    	
    	if($articlePointModels){
    		$this->addAll($articlePointModels);
    	}
    	
    	if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
    		$this->saveViewPoint($articlePointModels,$articleId);
    	}
    }
    
    /**
     * 文章热点同步老数据
     * @param : Array \haibao\cms\model\data\ArticlePointModel
     */
    private function saveViewPoint($articlePointModels,$articleId){
    	
    	
    	// DO : 根据$articleId 获得老数据的document_id
    	$documentId = 0;
    	$sql ='select OldPrimaryKey from `DataMigrationMap` where TableName=%s and PrimaryKey=%s';
    	$result = $this->query($sql,array('Article',$articleId));
    	while($result->fetch_assoc()){
    		
    		$documentId = $result->getData('OldPrimaryKey');
    	}
    	
    	if($documentId){
	    	$this->initOldDB();
	    	// DO : 删除上一次文章看点
	    	$sql = 'delete from viewpoint where article_id = %s';
	    	$this->query($sql,array($documentId));
	    	
	    	$sql='insert into viewpoint (article_id,';
	    	$sqlArr = $valArr = array();
	    	array_push($valArr, $documentId);
	    	$i = 1;
	    	foreach($articlePointModels as $key=>$model){
	    		
	    		if($model->PageNum <=7){
	    			$i++;
	    			$sql .='title'.$model->PageNum.',page_num'.$model->PageNum.',';
	    			array_push($valArr,$model->Title,$model->PageNum);
	    		}
	    	}
	    	$sqlArr = array_pad($sqlArr,2*$i-1, '%s');
	    	$sql = substr($sql,0,strlen($sql)-1).') values ';
	    	$sql .= '('.implode(',',$sqlArr).')';
	    	$this->query($sql,$valArr);
    	}
    }
    private function initNewDB() {
    	$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
    	return $this;
    }
    private function initOldDB() {
    	$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
    	return $this;
    }
}
